package export

import (
	"fmt"
	"game/game-design/loader"
	"os"
	"path/filepath"
	"strings"

	"github.com/xuri/excelize"
)

type ExcelIO struct{}

func (e *ExcelIO) Read(fileFullName string, designDefine *loader.DesignDefine) ([]*loader.DesignFile, error) {
	var designFiles []*loader.DesignFile = make([]*loader.DesignFile, 0)
	file0, err := os.Open(fileFullName)
	if err != nil {
		return designFiles, err
	}
	file, err := excelize.OpenReader(file0)
	if err != nil {
		fmt.Println(err)
		return designFiles, err
	}

	sheetList := file.GetSheetMap()
	for _, sheetName := range sheetList {
		rows := file.GetRows(sheetName)
		//excel文件会存在多个sheet，因此文件名需要拼接sheet的名字
		fileName := filepath.Base(file0.Name())
		var dFileName string
		if file.SheetCount == 1 {
			dFileName = strings.Replace(fileName, ".xlsx", "", 1)
		} else {
			dFileName = strings.Replace(fileName, ".xlsx", "", 1) + "_" + sheetName
		}
		dFile, err := loader.NewDesignFile(dFileName, rows, designDefine)
		if err == nil {
			designFiles = append(designFiles, dFile)
		}
	}
	return designFiles, nil
}

func (e *ExcelIO) Write(designFile *loader.DesignFile, outputPath string, expectType string) {
	os.Mkdir(outputPath, 0755)
	if !designFile.FileNeedExport(expectType) {
		fmt.Println(expectType, "导出忽略\t", designFile.Name)
		return
	}
	file := excelize.NewFile()
	sheetName := designFile.ClassName
	file.SetActiveSheet(1)
	file.SetSheetName(file.GetSheetName(1), sheetName)

	names := make([]string, 0)
	forms := make([]string, 0)
	tags := make([]string, 0)
	comments := make([]string, 0)

	for _, field := range designFile.Fields {
		needExport := designFile.FieldNeedExport(field.Tag(), expectType)
		if !needExport {
			continue
		}
		names = append(names, field.Name())
		forms = append(forms, field.Form())
		tags = append(tags, field.Tag())
		comments = append(comments, field.Comment())
	}

	file.SetSheetRow(sheetName, "A1", &designFile.Macros)
	file.SetSheetRow(sheetName, fmt.Sprintf("A%d", designFile.DesignDefine.NameOffset+1), &names)
	file.SetSheetRow(sheetName, fmt.Sprintf("A%d", designFile.DesignDefine.TypeOffset+1), &forms)
	file.SetSheetRow(sheetName, fmt.Sprintf("A%d", designFile.DesignDefine.TagOffset+1), &tags)
	file.SetSheetRow(sheetName, fmt.Sprintf("A%d", designFile.DesignDefine.CommentOffset+1), &comments)

	offset := 6
	line := 0
	for _, data := range designFile.Datas {
		var rowDatas []string
		for i, field := range designFile.Fields {
			needExport := designFile.FieldNeedExport(field.Tag(), expectType)
			if !needExport {
				continue
			}
			if i >= len(data) {
				rowDatas = append(rowDatas, "")
			} else {
				rowDatas = append(rowDatas, data[i])
			}
		}
		file.SetSheetRow(sheetName, fmt.Sprintf("A%d", offset+line), &rowDatas)
		line += 1
	}
	file.SaveAs(fmt.Sprintf("%s%s", outputPath, designFile.GetOutputName()+".xlsx"))
	fmt.Println("导出", designFile.Name)
}
